﻿using QD.Tools;
using QD_Clients.Code;
using QD_Clients.Code.DbContent;
using QD_Clients.Models;
using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;

namespace QD_Clients.Tester
{
    public partial class Test_Process : BaseForm
    {
        private int PageSize = 500;
        private int TotalPage = 1;
        private PageState PageState = PageState.Browse;

        //是否按用户过滤BUG
        private bool isfiterUid = true;

        /// <summary>
        /// BUG编号
        /// </summary>
        private string _TSID
        {
            get
            {
                return this.latsId.Text.Trim();
            }
            set
            {
                this.latsId.Text = value;
            }
        }

        public Test_Process()
        {
            InitializeComponent();
        }

        private void Test_Process_Load(object sender, EventArgs e)
        {
            this.navigator.BindingSource = this.bindingSource;
            this.bugList.DataSource = this.bindingSource;

            this.bugList.InitGrid(false, false, true);
            //this.bugList.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

            this.richTxtTools1.RichText = this.BUGContext;
            DataBind();

            this.latsId.Text =
            this.bugName.Text =
                this.refName.Text =
                this.submitToName.Text =
                this.createdate.Text =
                this.creatorname.Text = "";

            ProgramHelper.InitPrgoramItemTree(this.programDetailList);
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.curPageIndex.Text != "1")
            {
                this.curPageIndex.Text = "1";
            }
            else
            {
                DataBind();
            }
        }

        private void navigator_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            try
            {
                int pageIndex = GetCurPageIndex();

                switch (e.ClickedItem.Text)
                {
                    case "上一页":
                        {
                            if (pageIndex == 1)
                            {
                                QD.Tools.PromptHelper.Prompt("已经是第一页了！");
                            }
                            else
                            {
                                this.curPageIndex.Text = (--pageIndex).ToString();
                            }

                            break;
                        }
                    case "下一页":
                        {
                            if (pageIndex == TotalPage)
                            {
                                QD.Tools.PromptHelper.Prompt("已经是最后一页了！");
                            }
                            else
                            {
                                this.curPageIndex.Text = (++pageIndex).ToString();
                            }

                            break;
                        }
                }
            }
            catch (Exception ex)
            {
                QD.Tools.PromptHelper.Prompt(ex);
            }
        }

        private int GetCurPageIndex()
        {
            int pageIndex = 1;
            string txtCurPageIndex = this.curPageIndex.Text.Trim();
            if (string.IsNullOrEmpty(txtCurPageIndex))
            {
                throw new Exception("请输入正确的页码！");
            }
            else if (!int.TryParse(txtCurPageIndex, out pageIndex))
            {
                throw new Exception("请输入正确的页码！");
            }
            return pageIndex;
        }

        private void DataBind()
        {
            try
            {
                if (!string.IsNullOrEmpty(this.curPageIndex.Text.Trim()))
                {
                    int pageIndex = GetCurPageIndex();
                    string filter = getFilter();
                    DbConfigData db = new DbConfigData();
                    string sql1 = "select top 100  percent  ROW_NUMBER() over(order by LastProcessDate desc) as AID,* from Test_BUG where " + filter + " order by LastProcessDate desc";
                    string sql2 = string.Format("select  top {0} TSID,'['+SubmitToName+'] '+BUGName as BUGName,CreateDate from ({1}) t where AID>{2} order by AID asc", PageSize, sql1, ((pageIndex - 1) * PageSize).ToString());
                    DataTable dt = db.Query(sql2);
                    this.bindingSource.DataSource = dt;

                    object qtywaitProcess = db.ExecuteScalar("select count(*) from Test_BUG where " + getFilter("tpWaitProcess"));
                    this.tpWaitProcess.Text = "待处理(" + qtywaitProcess.ToString() + ")";

                    object qtySubmit = db.ExecuteScalar("select count(*) from Test_BUG where " + getFilter("tpSubmit"));
                    this.tpSubmit.Text = "已提交(" + qtySubmit.ToString() + ")";

                    object qtyFinish = db.ExecuteScalar("select count(*) from Test_BUG where " + getFilter("tpFinish"));
                    this.tpFinish.Text = "已完成(" + qtyFinish.ToString() + ")";

                    object qtyRecall = db.ExecuteScalar("select count(*) from Test_BUG where " + getFilter("tpRecall"));
                    this.tpRecall.Text = "已撤消(" + qtyRecall.ToString() + ")";

                    switch (this.tabControl1.SelectedTab.Name)
                    {
                        case "tpWaitProcess":
                            this.totalCount.Text = qtywaitProcess.ToString();
                            TotalPage = Convert.ToInt32(Math.Ceiling((decimal)(Convert.ToInt32(qtywaitProcess) * 1.0 / PageSize)));
                            break;
                        case "tpSubmit":
                            this.totalCount.Text = qtySubmit.ToString();
                            TotalPage = Convert.ToInt32(Math.Ceiling((decimal)(Convert.ToInt32(qtySubmit) * 1.0 / PageSize)));
                            break;
                        case "tpFinish":
                            this.totalCount.Text = qtyFinish.ToString();
                            TotalPage = Convert.ToInt32(Math.Ceiling((decimal)(Convert.ToInt32(qtyFinish) * 1.0 / PageSize)));
                            break;
                        case "tpRecall":
                            this.totalCount.Text = qtyRecall.ToString();
                            TotalPage = Convert.ToInt32(Math.Ceiling((decimal)(Convert.ToInt32(qtyRecall) * 1.0 / PageSize)));
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                QD.Tools.PromptHelper.Prompt(ex);
            }
        }

        private string getFilter()
        {
            string filter = getFilter(this.tabControl1.SelectedTab.Name);

            string _keyTxt = this.txtKey.Text.Trim();
            if (!string.IsNullOrEmpty(_keyTxt))
            {
                if (!string.IsNullOrEmpty(filter))
                {
                    filter += " and ";
                }
                filter += string.Format("(BUGName like '%{0}%' or TSID like '%{0}%')", _keyTxt);
            }

            string _filter;
            if (!string.IsNullOrEmpty(filter))
            {
                _filter = "(" + filter + ")";
            }
            else
            {
                _filter = filter;
            }

            return _filter;
        }

        private string getFilter(string bug_status)
        {
            string filter = "";
            if (QDUserHelper.CurUser.IsManager || !isfiterUid)
            {
                switch (bug_status)
                {
                    case "tpWaitProcess": //待处理
                        {
                            filter = string.Format("Status='{0}'", TestStatus.waitingProcess.ToString());
                            break;
                        }
                    case "tpSubmit": //已提交
                        {
                            filter = string.Format("Status='{0}'", TestStatus.waitingConfirm.ToString());
                            break;
                        }
                    case "tpFinish": //已处理
                        {
                            filter = string.Format("Status='{0}'", TestStatus.finish.ToString());
                            break;
                        }
                    case "tpRecall": //已撤消
                        {
                            filter = string.Format("Status='{0}'", TestStatus.recall.ToString());
                            break;
                        }
                }
            }
            else
            {
                switch (bug_status)
                {
                    case "tpWaitProcess": //待处理
                        {
                            filter = string.Format("NextProcessorCode='{0}' and Status='{1}'", QDUserHelper.CurUser.Uid, TestStatus.waitingProcess.ToString());
                            break;
                        }
                    case "tpSubmit": //已提交
                        {
                            filter = string.Format("SubmitToCode='{0}' and Status='{1}'", QDUserHelper.CurUser.Uid, TestStatus.waitingConfirm.ToString());
                            break;
                        }
                    case "tpFinish": //已处理
                        {
                            filter = string.Format("SubmitToCode='{0}' and Status='{1}'", QDUserHelper.CurUser.Uid, TestStatus.finish.ToString());
                            break;
                        }
                    case "tpRecall": //已撤消
                        {
                            filter = string.Format("SubmitToCode='{0}' and Status='{1}'", QDUserHelper.CurUser.Uid, TestStatus.recall.ToString());
                            break;
                        }
                }
            }

            return filter;
        }

        private void ts_Reload_Click(object sender, EventArgs e)
        {
            this.curPageIndex.Text = "1";
            isfiterUid = true;
            DataBind();
        }

        private void bugList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1 && e.ColumnIndex > -1)
            {
                string _tsid = this.bugList.Rows[e.RowIndex].Cells["listTSID"].Value.ToString();
                InitUIData(_tsid);
            }
        }

        public new void InitUIData(string tsid)
        {
            try
            {
                PageState = PageState.Browse;
                DbConfigData db = new DbConfigData();
                Test_BUG mst = db.Test_BUG.FirstOrDefault(p => p.TSID == tsid);

                if (mst != null)
                {
                    this._TSID = tsid;
                    this.bugName.Text = mst.BUGName;
                    if (!string.IsNullOrEmpty(mst.FilePath))
                    {
                        //System.IO.MemoryStream mstream = new System.IO.MemoryStream(mst.BUGContext, false);
                        //this.BUGContext.LoadFile(mstream, RichTextBoxStreamType.RichText);

                        byte[] b = RtfHelper.DownloadFiles(mst.FilePath);
                        RtfHelper.LoadRichTextBoxData(this.BUGContext, b);
                    }
                    else
                    {
                        this.BUGContext.Clear();
                    }

                    this.latsId.Text = mst.TSID;
                    this.refName.Text = mst.RefName;
                    this.submitToName.Text = mst.SubmitToName;
                    this.creatorname.Text = mst.CreatorName;
                    this.createdate.Text = mst.CreateDate.ToString("yyyy-MM-dd HH:mm:ss");
                    Test_BUGHelper.BindProcessList(this.listLog, this._TSID);
                }
                else
                {
                    throw new Exception("BUG[" + this._TSID + "]不存在或已经被删除！");
                }
            }
            catch (Exception ex)
            {
                PromptHelper.Prompt(ex);
            }
        }

        private Test_BUG IsCurrentExists(DbConfigData dbConfig)
        {
            Test_BUG mst = null;
            if (string.IsNullOrEmpty(this._TSID))
            {
                PromptHelper.Prompt("未加载任何BUG信息！");
            }
            else
            {
                mst = dbConfig.Test_BUG.FirstOrDefault(p => p.TSID == _TSID);

                if (mst == null)
                {
                    PromptHelper.Prompt("BUG [" + this._TSID + "] 未保存或已经被删除！");
                }
            }

            return mst;
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                if (PageState != PageState.Browse)
                {
                    throw new Exception("当前BUG未保存！");
                }
                DbConfigData dbConfig = new DbConfigData();
                Test_BUG mst = IsCurrentExists(dbConfig);
                if (mst != null)
                {
                    if (PromptHelper.PromptOkCancel("确认处理当前BUG？") == DialogResult.OK)
                    {

                        if (mst.Status == TestStatus.finish.ToString())
                        {
                            throw new Exception("当前BUG已完成！");
                        }
                        else if (mst.Status == TestStatus.recall.ToString())
                        {
                            throw new Exception("当前BUG已撤消！");
                        }
                        else if (mst.Status != TestStatus.waitingProcess.ToString())
                        {
                            throw new Exception("当前BUG测试未提交，不可以处理！");
                        }
                        else if (mst.NextProcessorCode != QDUserHelper.CurUser.Uid)
                        {
                            throw new Exception("当前BUG的处理人为[" + mst.NextProcessorName + "]！");
                        }

                        mst.LastProcessDate = DateTime.Now;
                        mst.NextProcessorCode = mst.CreatorCode;
                        mst.NextProcessorName = mst.CreatorName;
                        mst.Status = TestStatus.waitingConfirm.ToString();

                        Test_BUGHelper.AddBugProcessList(dbConfig, this._TSID, QDUserHelper.CurUser.Uid, QDUserHelper.CurUser.UName, this.ProcessDesc.Text.Trim(), "处理", mst.NextProcessorCode, mst.NextProcessorName);
                        dbConfig.SaveChanges();
                        PromptHelper.Prompt("提交成功！");
                        this.ProcessDesc.Clear();
                        Test_BUGHelper.BindProcessList(this.listLog, this._TSID);
                    }
                }
            }
            catch (Exception ex)
            {
                PromptHelper.Prompt(ex);
            }
        }

        private void t_monitoring_Tick(object sender, EventArgs e)
        {
            this.curPageIndex.Text = "1";
            DataBind();
        }

        private void refName_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (!string.IsNullOrEmpty(this._TSID))
            {
                DbConfigData db = new DbConfigData();
                Test_BUG mst = db.Test_BUG.First(p => p.TSID == this._TSID);

                if (!string.IsNullOrEmpty(mst.RefCode))
                {
                    ProgramHelper.BindProgramItem(this.programDetailList, mst.RefCode);
                }
            }
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            DataBind();
        }

        private void txtKey_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                toolStripButton6_Click(sender, e);
            }
        }

        private void curPageIndex_TextChanged(object sender, EventArgs e)
        {
            DataBind();
        }

        private void ts_prev_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_TSID))
            {
                PromptHelper.Prompt("未加载任何BUG信息！");
            }
            else
            {
                DbConfigData db = new DbConfigData();
                string filter = getFilter();
                string sql = string.Format("select top 1 TSID from Test_BUG where TSID>'{0}' and {1} order by TSID asc", _TSID, filter);
                object _tsId = db.ExecuteScalar(sql);
                if (_tsId == null || _tsId.ToString().Length == 0)
                {
                    PromptHelper.Prompt("已经是最后一条数据了！");
                }
                else
                {
                    InitUIData(_tsId.ToString());
                }
            }
        }

        private void ts_next_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_TSID))
            {
                PromptHelper.Prompt("未加载任何BUG信息！");
            }
            else
            {
                DbConfigData db = new DbConfigData();
                string filter = getFilter();
                string sql = string.Format("select top 1 TSID from Test_BUG where TSID<'{0}' and {1} order by TSID desc", _TSID, filter);
                object _tsId = db.ExecuteScalar(sql);
                if (_tsId == null || _tsId.ToString().Length == 0)
                {
                    PromptHelper.Prompt("已经是第一条数据了！");
                }
                else
                {
                    InitUIData(_tsId.ToString());
                }
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            this.curPageIndex.Text = "1";
            isfiterUid = false;
            DataBind();
        }
    }
}